package com.qianda.qdminiapp.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登出令牌处理器
 * @ClassName LogoutTokenHandler
 * @Author cw
 * @Date 2019/7/1 11:52
 **/
public class LogoutTokenHandler implements LogoutHandler {

    private final TokenManager tokenManager;

    /**
     * 创建登出令牌处理器
     *
     * @param tokenManager 令牌管理器
     */
    public LogoutTokenHandler(TokenManager tokenManager) {
        if (tokenManager == null) {
            throw new IllegalArgumentException("TokenManager is required");
        }
        this.tokenManager = tokenManager;
    }

    @Override
    public void logout(HttpServletRequest req,
                       HttpServletResponse resp,
                       Authentication auth) {

        // 登出需要传递令牌
        String tokenId = req.getHeader(com.qianda.qdminiapp.security.AuthenticationFilter.TOKEN_HEADER);
        if (StringUtils.isEmpty(tokenId)) {
            throw new InvalidTokenException();
        }

        // 使令牌失效
        tokenManager.invalidate(tokenId);

    }


}
